package com.jplus.orm.c3p0;

import java.beans.PropertyVetoException;

import javax.sql.DataSource;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.jplus.core.InstanceFactory;
import com.jplus.core.core.ConfigHandle;
import com.jplus.core.db.DataSourceFactory;
import com.jplus.core.plugin.Plugin;
import com.jplus.core.util.UUIDUtil;
import com.mchange.v2.c3p0.ComboPooledDataSource;

/**
 * C3p0Plugin
 * 
 * @author yuanqy
 *
 */
public class C3p0Plugin extends DataSourceFactory implements Plugin {
	Logger logger = LoggerFactory.getLogger(getClass());
	private ComboPooledDataSource dataSource;
	private String prefix = "db";

	@Override
	public void init() {
		try {
			dataSource = new ComboPooledDataSource();
			dataSource.setJdbcUrl(ConfigHandle.getString(prefix + ".url"));
			dataSource.setUser(ConfigHandle.getString(prefix + ".username"));
			dataSource.setPassword(ConfigHandle.getString(prefix + ".password"));
			dataSource.setDriverClass(ConfigHandle.getString(prefix + ".driver"));
			// ==public
			dataSource.setMaxPoolSize(ConfigHandle.getInt(prefix + ".maxPoolSize", 15));
			dataSource.setMinPoolSize(ConfigHandle.getInt(prefix + ".minPoolSize", 3));
			dataSource.setInitialPoolSize(ConfigHandle.getInt(prefix + ".initialPoolSize", 3));
			dataSource.setAcquireIncrement(ConfigHandle.getInt(prefix + ".acquireIncrement", 3));
			
			dataSource.setMaxIdleTime(ConfigHandle.getInt(prefix + ".maxIdleTime", 600));//单位秒
			dataSource.setCheckoutTimeout(ConfigHandle.getInt(prefix + ".checkoutTimeout", 5000));//单位毫秒

			ConfigHandle.setProp(InstanceFactory.DS_FACTORY, getClass().getName());
		} catch (PropertyVetoException e) {
			dataSource = null;
			logger.error("C3p0Plugin start error");
			throw new RuntimeException(e);
		}
	}

	public C3p0Plugin(String prefix) {
		this.prefix = prefix;
	}

	public C3p0Plugin(ComboPooledDataSource dataSource) {
		this.dataSource = dataSource;
	}

	public C3p0Plugin(String jdbcUrl, String user,String pwd, String driverClass) { 
		this.prefix = UUIDUtil.getUUID(6, 62);
		ConfigHandle.setProp(prefix + ".url", jdbcUrl);
		ConfigHandle.setProp(prefix + ".username", user);
		ConfigHandle.setProp(prefix + ".password", pwd);
		ConfigHandle.setProp(prefix + ".driver", driverClass);
		init();
	}

	public C3p0Plugin() {
	}

	@Override
	public void destroy() {
		dataSource.close();
	}

	@Override
	public DataSource getDataSource() {
		return dataSource;
	}

}
